package com.jmyd.commons.redis.repository;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.time.Clock;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;


@Repository
public class ObjectRedisHelper {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;


    public boolean isPresent(String key) {
        AtomicBoolean flag = new AtomicBoolean(false);
        Set<String> keys = this.redisTemplate.keys(key + ":*");
        Optional.ofNullable(keys).filter(strings -> keys.size() > 0).ifPresent(k -> {
            String s = k.toArray()[0].toString();
            String[] keySplit = s.split(":");
            String saveTime = keySplit[keySplit.length - 1];
            if (Clock.systemUTC().millis() - Long.parseLong(saveTime) > 0) {
                redisTemplate.delete(s);
                flag.set(false);
            } else {
                flag.set(true);
            }
        });
        return flag.get();
    }

    public boolean hasKey(String key) {
        Assert.notNull(key, "redis key is empty.");
        return redisTemplate.hasKey(key);
    }

    /**
     * 设置过期时间
     *
     * @param key        指定key
     * @param expireTime 过期时间
     * @param timeUnit   时间单位
     * @author samphin
     * @date 2021-3-26 14:55:34
     */
    public void expire(String key, long expireTime, TimeUnit timeUnit) {
        redisTemplate.expire(key, expireTime, timeUnit);
    }

    public void save(String key, Object value, long timeout) {
        String keys = key + ":" + (Clock.systemUTC().millis() + (timeout * 1000));
        redisTemplate.opsForValue().set(keys, value);
    }

    public void saveList(String key, Object value) {
        redisTemplate.opsForList().leftPushAll(key, value);
    }

    public List getList(String key) {
        return redisTemplate.opsForList().range(key, 0, -1);
    }

    public void save(String key, Object value, long expireTime, TimeUnit unit) {
        redisTemplate.opsForValue().set(key, value);
        redisTemplate.expire(key, expireTime, unit);
    }

    public Object getAll(String key) {
        Set<String> keys = this.redisTemplate.keys(key + ":*");
        if (CollectionUtils.isNotEmpty(keys)) {
            String s = keys.toArray()[0].toString();
            return redisTemplate.opsForValue().get(s);
        }
        return null;
    }

    public Object get(String key) {
        return this.redisTemplate.opsForValue().get(key);
    }

}
